package com.example.mqtt.config;

import com.example.mqtt.callback.MqttMessageCallBack;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

/**
 * 配置类，创建发送消息和接受消息的客户端
 */
@Slf4j
@Configuration
public class MqttClientConfig {

    @Autowired
    private MqttMessageCallBack mqttMessageCallBack;
    @Autowired
    private MqttProperties mqttProperties;

    @Bean("mqttConnectOptions")
    public MqttConnectOptions getOption(){

        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(mqttProperties.getUsername());
        options.setPassword(mqttProperties.getPassword().toCharArray());
        options.setConnectionTimeout(mqttProperties.getTimeout());
        options.setKeepAliveInterval(mqttProperties.getKeepAlive());
        options.setCleanSession(true);
        options.setAutomaticReconnect(false);

        return options;
    }

    /**
     * 发布消息客户端
     * @return
     */
    @Bean("sendMqttClient")
    public MqttClient getSendMqttClient(MqttConnectOptions options){
        MqttClient mqttClient = null;
        try {
            mqttClient = new MqttClient(mqttProperties.getHostUrl(),mqttProperties.getSendClientId() , new MemoryPersistence());
            try {
                // 设置回调
                mqttClient.setCallback(mqttMessageCallBack);
                //mqttClient.connect(options);
                IMqttToken iMqttToken = mqttClient.connectWithResult(options);
                boolean complete = iMqttToken.isComplete();
                log.info("发送端MQTT连接"+(complete?"成功":"失败"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mqttClient;
    }

    /**
     * 接收消息客户端
     * @return
     */
    @Bean("subMqttClient")
    public MqttClient getSubMqttClient(MqttConnectOptions options){
        MqttClient mqttClient = null;
        try {
            mqttClient = new MqttClient(mqttProperties.getHostUrl(),mqttProperties.getSubClientId() , new MemoryPersistence());
            try {
                // 设置回调
                mqttClient.setCallback(mqttMessageCallBack);
                //mqttClient.connect(options);
                IMqttToken iMqttToken = mqttClient.connectWithResult(options);
                boolean complete = iMqttToken.isComplete();
                log.info("接收端MQTT连接"+(complete?"成功":"失败"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return mqttClient;
    }
}
